package com.example.fragment;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentOnAttachListener;

import com.example.fragment.databinding.ActivityLifecycleBinding;

public class LifecycleActivity extends AppCompatActivity {
    private static final String TAG = "LifecycleActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityLifecycleBinding binding = ActivityLifecycleBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Log.d(TAG, "Activity:onCreate");

        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragment_container);
        if (currentFragment == null) {
            final Fragment fragment = BlankFragment.newInstance("生命周期过程");
            fragmentManager.beginTransaction()
                    .add(R.id.fragment_container, fragment, "title")
                    .commit();

            // 用于监听Fragment的附加事件， onAttachFragment()已废弃
            fragmentManager.addFragmentOnAttachListener(new FragmentOnAttachListener() {
                @Override
                public void onAttachFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment) {
                    Log.d(TAG, String.format("Fragment %s is attached", fragment.getId()));
                }
            });
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Activity:onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "Activity:onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "Activity:onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "Activity:onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Activity:onDestroy");
    }
}